package cn.edu.scau.cmi.ema.controller.rest;

import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.io.IOException;

import com.google.gson.Gson;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;


import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiPsonService;
import cn.edu.scau.cmi.ema.base.CmiEmaController;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.service.*;

import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.WebDataBinder;

@Controller("MaterialRestController")
public class MaterialRestController extends CmiEmaController {

	/**
	 * Create a new Material entity
	 * 
	 */
	@RequestMapping(value = "/newMaterial", method = RequestMethod.POST)
	@ResponseBody
	public Object newMaterial(@RequestBody Material material) {
		materialService.saveMaterial(material);
		return JSONObject.parse(cmiPsonService.toJsonString(materialDAO.findMaterialByPrimaryKey(material.getId()), 2));
	}

	@RequestMapping(value = "/restNewMaterial", method = RequestMethod.POST)
	@ResponseBody
	public Object restNewMaterial(@RequestBody String materialJson) {
		Material material = new Gson().fromJson(materialJson, Material.class);
		appendReferences(material);
		materialService.saveMaterial(material);
		return JSONObject.parse(cmiPsonService.toJsonString(materialDAO.findMaterialByPrimaryKey(material.getId()), 2));
	}

	@RequestMapping(value = "/saveMaterial", method = RequestMethod.PUT)
	@ResponseBody
	public Material saveMaterial(@RequestBody Material material) {
		materialService.saveMaterial(material);
		return materialDAO.findMaterialByPrimaryKey(material.getId());
	}

	@RequestMapping(value = "/restSaveMaterial", method = RequestMethod.PUT)
	@ResponseBody
	public Object restSaveMaterial(@RequestBody String materialJson) {
		Material material = new Gson().fromJson(materialJson, Material.class);
		appendReferences(material);
		CmiPsonService cmiPsonService = new CmiPsonService();
		materialService.saveMaterial(material);
		return JSONObject.parse(cmiPsonService.toJsonString(materialDAO.findMaterialByPrimaryKey(material.getId()), 1));
	}

	@RequestMapping(value = "/restDeleteMaterial/{materialId}", method = RequestMethod.DELETE)
	@ResponseBody
	public void restDeleteMaterial(@PathVariable Integer materialId) {
		Material material = materialDAO.findMaterialByPrimaryKey(materialId);
		materialService.deleteMaterial(material);
	}

	@RequestMapping(value = "/restConfirmDeleteMaterials")
	@ResponseBody
	public Object restConfirmDeleteMaterials(@RequestBody Set<Integer> deleteMaterialsIds) {
		Set<Material> deleteMaterials = materialDAO.findMaterialsByIds(deleteMaterialsIds);
		Set<Material> referencedMaterials = materialService.loadReferenceMaterials(deleteMaterials);
		deleteMaterials.removeAll(referencedMaterials);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("referencedEntitys", referencedMaterials);
		jsonObject.put("deleteEntitys", deleteMaterials);
		return JSONObject.parse(jsonObject.toJSONString());
	}

	@RequestMapping("/restDeleteMaterials")
	@ResponseBody
	public Object restDeleteMaterials(@RequestBody Set<Material> deleteMaterials) {
		Iterator<Material> iterator = deleteMaterials.iterator();
		while (iterator.hasNext()) {
			Material currentMaterial = iterator.next();
			materialService.deleteMaterial(currentMaterial);
		}
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("url", "listMaterials");
		return JSONObject.parse(jsonObject.toJSONString());
	}
	// loadself

	@RequestMapping(value = "/restLoadMaterial/{materialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadMaterial(@PathVariable Integer materialId, @RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject
				.parse(cmiPsonService.toPsonString(materialDAO.findMaterialByPrimaryKey(materialId), 2, cmiPagination));
	}
	// loadReferenceds
	// TODO loadReferencedsPson，这个方法有一些问题，待修复

	@RequestMapping(value = "/restLoadMaterialFoodbatchmaterials/{materialId}/foodbatchmaterials/{relatedfoodbatchmaterialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadMaterialFoodbatchmaterials(@PathVariable Integer materialId,
			@PathVariable Integer relatedfoodbatchmaterialId, @RequestBody CmiPagination cmiPagination) {
		Foodbatchmaterial foodbatchmaterial = foodbatchmaterialDAO
				.findFoodbatchmaterialByPrimaryKey(relatedfoodbatchmaterialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodbatchmaterial, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadMaterialFoodmaterials/{materialId}/foodmaterials/{relatedfoodmaterialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadMaterialFoodmaterials(@PathVariable Integer materialId,
			@PathVariable Integer relatedfoodmaterialId, @RequestBody CmiPagination cmiPagination) {
		Foodmaterial foodmaterial = foodmaterialDAO.findFoodmaterialByPrimaryKey(relatedfoodmaterialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(foodmaterial, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadMaterialMaterialaddresss/{materialId}/materialaddresss/{relatedmaterialaddressId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadMaterialMaterialaddresss(@PathVariable Integer materialId,
			@PathVariable Integer relatedmaterialaddressId, @RequestBody CmiPagination cmiPagination) {
		Materialaddress materialaddress = materialaddressDAO.findMaterialaddressByPrimaryKey(relatedmaterialaddressId,
				-1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(materialaddress, 2, cmiPagination));
	}

	@RequestMapping(value = "/restLoadMaterialPurchasematerials/{materialId}/purchasematerials/{relatedpurchasematerialId}", method = RequestMethod.POST)
	@ResponseBody
	public Object restLoadMaterialPurchasematerials(@PathVariable Integer materialId,
			@PathVariable Integer relatedpurchasematerialId, @RequestBody CmiPagination cmiPagination) {
		Purchasematerial purchasematerial = purchasematerialDAO
				.findPurchasematerialByPrimaryKey(relatedpurchasematerialId, -1, -1);
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(purchasematerial, 2, cmiPagination));
	}

	public void appendReferences(Material material) {

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodbatchmaterial> foodbatchmaterialsForMaterial = new HashSet<>();
		for (Foodbatchmaterial foodbatchmaterial_Material : material.getFoodbatchmaterialsForMaterial()) {
			foodbatchmaterialsForMaterial.add(
					foodbatchmaterialService.findFoodbatchmaterialByPrimaryKey(foodbatchmaterial_Material.getId()));
		}
		material.setFoodbatchmaterialsForMaterial(foodbatchmaterialsForMaterial);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Foodmaterial> foodmaterialsForMaterial = new HashSet<>();
		for (Foodmaterial foodmaterial_Material : material.getFoodmaterialsForMaterial()) {
			foodmaterialsForMaterial
					.add(foodmaterialService.findFoodmaterialByPrimaryKey(foodmaterial_Material.getId()));
		}
		material.setFoodmaterialsForMaterial(foodmaterialsForMaterial);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Materialaddress> materialaddresssForMaterial = new HashSet<>();
		for (Materialaddress materialaddress_Material : material.getMaterialaddresssForMaterial()) {
			materialaddresssForMaterial
					.add(materialaddressService.findMaterialaddressByPrimaryKey(materialaddress_Material.getId()));
		}
		material.setMaterialaddresssForMaterial(materialaddresssForMaterial);

		// 引用表不是纯联系表，引用数量大于或者等于2
		Set<Purchasematerial> purchasematerialsForMaterial = new HashSet<>();
		for (Purchasematerial purchasematerial_Material : material.getPurchasematerialsForMaterial()) {
			purchasematerialsForMaterial
					.add(purchasematerialService.findPurchasematerialByPrimaryKey(purchasematerial_Material.getId()));
		}
		material.setPurchasematerialsForMaterial(purchasematerialsForMaterial);
	}

	@RequestMapping(value = "/restGetMaterialFoodbatchmaterials/{materialId}/foodbatchmaterials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetMaterialFoodbatchmaterials(@PathVariable Integer materialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				materialDAO.findMaterialByPrimaryKey(materialId).getFoodbatchmaterialsForMaterial(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetMaterialFoodmaterials/{materialId}/foodmaterials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetMaterialFoodmaterials(@PathVariable Integer materialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				materialDAO.findMaterialByPrimaryKey(materialId).getFoodmaterialsForMaterial(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetMaterialMaterialaddresss/{materialId}/materialaddresss", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetMaterialMaterialaddresss(@PathVariable Integer materialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				materialDAO.findMaterialByPrimaryKey(materialId).getMaterialaddresssForMaterial(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restGetMaterialPurchasematerials/{materialId}/purchasematerials", method = RequestMethod.POST)
	@ResponseBody
	public Object restGetMaterialPurchasematerials(@PathVariable Integer materialId,
			@RequestBody CmiPagination cmiPagination) {
		CmiPsonService cmiPsonService = new CmiPsonService();
		return JSONObject.parse(cmiPsonService.toPsonString(
				materialDAO.findMaterialByPrimaryKey(materialId).getPurchasematerialsForMaterial(), 2, cmiPagination));
	}

	@RequestMapping(value = "/restListMaterials", method = RequestMethod.GET)
	@ResponseBody
	public Object restListMaterials() {
		return JSONObject.parse(cmiPsonService.toJsonString(materialService.loadMaterials(), 2));
	}

	@RequestMapping(value = "/restListMaterialsPost", method = RequestMethod.POST)
	@ResponseBody
	public Object restListMaterialsPost(@RequestBody CmiPagination cmiPagination) {

		CmiPsonService cmiPsonService = new CmiPsonService();
		cmiPagination = materialPaginationService.updateAppPagination(cmiPagination);
		int startResult = (cmiPagination.getCurrentPagination() - 1) * cmiPagination.getPaginationSize();

		Set<Material> materials = materialDAO.findAllMaterials(startResult, cmiPagination.getPaginationSize());
		String materialString = cmiPsonService.toPsonString(materials, 2, cmiPagination);

		return JSONObject.parse(materialString);
	}

	@RequestMapping("/materialSelectBox")
	@ResponseBody
	public JSONObject materialSelectBox(@RequestParam(required = false) String searchTable,
			@RequestParam(required = false) Set<Integer> searchValue, // 杨宏宇2019-9-10：searchValue是在selectpage.js的616行定义，如果要修改searchValue的名称，1.可以修改在selectpage.js修改；2.可以
																		// @RequestParam(value="searchValue", required =
																		// false) Set<Integer> someName
			@RequestParam(required = false, defaultValue = "10") int paginationSize,
			@RequestParam(required = false, defaultValue = "1") int pageNumber,
			@RequestParam(value = "qWord[]", required = false) String queryword,
			@RequestParam(required = false) String selectItem) throws IOException {
		Set entitySet = null;
		Integer count = 0;

		// 初始化原始值

		if (searchValue != null) {
			switch (searchTable) {
			// 外键

			// 被引用键
			case "Foodbatchmaterial":
				entitySet = foodbatchmaterialService.loadFoodbatchmaterialsByIdSet(searchValue);
				break;
			case "Foodmaterial":
				entitySet = foodmaterialService.loadFoodmaterialsByIdSet(searchValue);
				break;
			case "Materialaddress":
				entitySet = materialaddressService.loadMaterialaddresssByIdSet(searchValue);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialService.loadPurchasematerialsByIdSet(searchValue);
				break;
			}
			// 没有测试，深度需要多少？？？
			String jsonData = cmiPsonService.toJsonString(entitySet, 1);
			JSONArray jsonArray = new JSONArray();
			jsonArray = (JSONArray) JSON.parse((String) jsonData);

			JSONObject jsonObject = new JSONObject();
			jsonObject.put("list", jsonArray);
			jsonObject.put("totalRow", entitySet.size());
			return jsonObject;
		}

		// 不根据关键字进行搜索
		if (queryword == null || queryword.trim() == "") {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Foodbatchmaterial":
				entitySet = foodbatchmaterialDAO.findAllFoodbatchmaterials((pageNumber - 1) * paginationSize,
						paginationSize);
				count = foodbatchmaterialService.countFoodbatchmaterials();
				break;
			case "Foodmaterial":
				entitySet = foodmaterialDAO.findAllFoodmaterials((pageNumber - 1) * paginationSize, paginationSize);
				count = foodmaterialService.countFoodmaterials();
				break;
			case "Materialaddress":
				entitySet = materialaddressDAO.findAllMaterialaddresss((pageNumber - 1) * paginationSize,
						paginationSize);
				count = materialaddressService.countMaterialaddresss();
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findAllPurchasematerials((pageNumber - 1) * paginationSize,
						paginationSize);
				count = purchasematerialService.countPurchasematerials();
				break;
			}
		} else {
			switch (selectItem) {
			// 外键

			// 被引用键
			case "Foodbatchmaterial":
				entitySet = foodbatchmaterialDAO.findFoodbatchmaterialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodbatchmaterialService.countFoodbatchmaterialsByName(queryword);
				break;
			case "Foodmaterial":
				entitySet = foodmaterialDAO.findFoodmaterialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = foodmaterialService.countFoodmaterialsByName(queryword);
				break;
			case "Materialaddress":
				entitySet = materialaddressDAO.findMaterialaddressByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = materialaddressService.countMaterialaddresssByName(queryword);
				break;
			case "Purchasematerial":
				entitySet = purchasematerialDAO.findPurchasematerialByNameContaining(queryword,
						(pageNumber - 1) * paginationSize, paginationSize);
				count = purchasematerialService.countPurchasematerialsByName(queryword);
				break;
			}
		}
		/**
		 * 将Json数据转换成jsonArray形式，需要通过pson方式进行转换，然后再转换成JsonArray。因为存在懒加载
		 * 没有直接使用CmiPsonService中的fromJson方法是因为，fromJson方法会将int类型的直接转换成double类型的数据，这个问题还没有解决
		 */
		// 没有测试，深度需要多少？？？
		String jsonData = cmiPsonService.toJsonString(entitySet, 1);
		JSONArray jsonArray = new JSONArray();
		jsonArray = (JSONArray) JSON.parse((String) jsonData);

		JSONObject jsonObject = new JSONObject();
		jsonObject.put("list", jsonArray);
		jsonObject.put("paginationSize", paginationSize);
		jsonObject.put("pageNumber", pageNumber);
		jsonObject.put("totalRow", count);
		jsonObject.put("totalPaginations",
				count % paginationSize == 0 ? count / paginationSize : count / paginationSize + 1);
		return jsonObject;
	}
}
